package io.renren.modules.noc.controller;

import java.util.*;


import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.noc.entity.NocBusinessLabelEntity;
import io.renren.modules.noc.entity.NocMemberLabelEntity;
import io.renren.modules.noc.entity.NocTemplateEntity;
import io.renren.modules.noc.service.NocBusinessLabelService;
import io.renren.modules.noc.service.NocMemberLabelService;
import io.renren.modules.noc.service.NocTemplateService;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.shiro.ShiroUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.renren.modules.noc.entity.NocBusinessEntity;
import io.renren.modules.noc.service.NocBusinessService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;

import javax.servlet.http.HttpServletRequest;


/**
 * 展商数据表
 *
 * @author whc
 * @email hucheng_86@126.com
 * @date 2019-07-02 15:17:18
 */
@RestController
@RequestMapping("noc/nocbusiness")
public class NocBusinessController extends BaseController{
    @Autowired
    private NocBusinessService nocBusinessService;
    @Autowired
    private NocTemplateService nocTemplateService;
    @Autowired
    private NocBusinessLabelService nocBusinessLabelService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("noc:nocbusiness:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = nocBusinessService.queryPage(params);

        return R.ok().put("page", page);
    }

    /*@RequestMapping("/list")
    @RequiresPermissions("noc:nocbusiness:list")
    public List<NocBusinessEntity> listAll(@RequestParam Map<String, Object> params){
        SysUserEntity userEntity = ShiroUtils.getUserEntity();
        Map<String,Object> p = new HashMap<String,Object>();
        p.put("mobile",params.get("mobile"));
        p.put("company",params.get("company"));
        if(!"admin".equals(userEntity.getUsername())){
            p.put("ly",userEntity.getRemark());
        }
        List<NocBusinessEntity> list = (List<NocBusinessEntity>) nocBusinessService.listByMap(p);
        return list;
    }*/

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("noc:nocbusiness:info")
    public R info(@PathVariable("id") Integer id){
        NocBusinessEntity nocBusiness = nocBusinessService.getById(id);

        Integer txid ;
        if(nocBusiness.getTxid()==null){
            txid = nocBusiness.getId();
        }else{
            txid = nocBusiness.getTxid();
        }
        Map<String,Object> p = new HashMap<>();
        p.put("member_id",id);
        List<NocBusinessLabelEntity> labes =  (List<NocBusinessLabelEntity>)nocBusinessLabelService.listByMap(p);
        Map<String,Object> map = new HashMap<>();
        map.put("nocBusiness", nocBusiness);
        map.put("txid",txid);
        map.put("labels",labes);

        return R.ok(map);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("noc:nocbusiness:save")
    public R save(@RequestBody NocBusinessEntity nocBusiness, HttpServletRequest req) {


        Integer txid = nocBusiness.getTxid();
        Integer tid = nocBusiness.getTid();
        if(txid!=null){
            Map<String,Object> m = new HashMap<>();
            m.put("txid",txid);
            m.put("tid",tid);
            Integer count = nocBusinessService.getMemberCount(m);
            Integer member = nocBusinessService.getMember(m);
            if(member<count|member==count){
                return R.error(1,"同行人已超过最大人数");
            }
        }
        SysUserEntity user = ShiroUtils.getUserEntity();
        //链接处理
        StringBuffer url = req.getRequestURL();
        String shortUrl = url.delete(url.length() - req.getRequestURI().length(), url.length()).append("/").toString();
        shortUrl = shortUrl.replace("http://", "").replace("https://", "");
        NocTemplateEntity template = nocTemplateService.getById(nocBusiness.getTid());

        Map<String, Object> p = new HashMap<>();
        p.put("mobile", nocBusiness.getMobile());
        p.put("tid", nocBusiness.getTid());
        List<NocBusinessEntity> list = (List<NocBusinessEntity>) nocBusinessService.listByMap(p);
        if (list != null && list.size() > 0) {
            return R.error(1,"手机号已被注册");
        } else {
            nocBusiness.setLy(user.getRemark());
            nocBusiness.setErcode(this.getNextErCodeBusi());
            nocBusiness.setCreateTime(new Date());
            /*Integer txid = nocBusiness.getTxid();
            if(txid==null){
                nocBusiness.setTxid(nocBusiness.getId());
            }else{
                nocBusiness.setTxid(nocBusiness.getTxid());
            }*/
            nocBusinessService.save(nocBusiness);

            //添加标签
            String labels = nocBusiness.getLabelIds();
            if(StringUtils.isNotEmpty(labels)){
                String[] lbs = labels.split(",");
                for(String lbid:lbs){
                    NocBusinessLabelEntity labelEntity = new NocBusinessLabelEntity();
                    labelEntity.setLabelId(Integer.parseInt(lbid));
                    labelEntity.setMemberId(nocBusiness.getId());
                    nocBusinessLabelService.save(labelEntity);
                }
            }

            if("0".equals(nocBusiness.getIsman())) {
                //发送短信
                String _url = shortUrl + "s/" + nocBusiness.getId();
                String content = "尊敬的" + nocBusiness.getName() + ",您" + template.getTemplate() + "的展商电子门票链接 " + _url + " ,请直接现场刷闸机入场";
                System.out.println(content);
                this.sendContentMsg(nocBusiness.getTid() + "", nocBusiness.getMobile(), content);
            }
        }

       /* SysUserEntity userEntity = ShiroUtils.getUserEntity();
        nocBusiness.setUpdator(userEntity.getRemark());
        nocBusiness.setCreateTime(new Date());
        nocBusiness.setUpdateTime(new Date());
        nocBusiness.setErcode(this.getNextErCodeBusi());
        nocBusinessService.save(nocBusiness);*/

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("noc:nocbusiness:update")
    public R update(@RequestBody NocBusinessEntity nocBusiness){
        SysUserEntity userEntity = ShiroUtils.getUserEntity();
        nocBusiness.setUpdator(userEntity.getRemark());
        nocBusiness.setUpdateTime(new Date());
        ValidatorUtils.validateEntity(nocBusiness);

        //添加标签
        Map<String,Object> delMap = new HashMap<>();
        delMap.put("member_id",nocBusiness.getId());
        nocBusinessLabelService.removeByMap(delMap);
        String labels = nocBusiness.getLabelIds();
        if(StringUtils.isNotEmpty(labels)){
            String[]  lbs = labels.split(",");
            for(String lbid:lbs){
                NocBusinessLabelEntity labelEntity = new NocBusinessLabelEntity();
                labelEntity.setLabelId(Integer.parseInt(lbid));
                labelEntity.setMemberId(nocBusiness.getId());
                nocBusinessLabelService.save(labelEntity);
            }
        }

        if(nocBusiness.getTxid()!=null){
            nocBusinessService.updateById(nocBusiness);
            return R.ok();
        }
        nocBusinessService.updateById(nocBusiness);
        Integer txid = nocBusiness.getId();
        String company = nocBusiness.getCompany();
        Map<String,Object> map = new HashMap<>();
        map.put("txid",txid);
        map.put("company",company);
        nocBusinessService.updateCompany(map);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("noc:nocbusiness:delete")
    public R delete(@RequestBody Integer[] ids){
        nocBusinessService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
